package com.yanqu.road.server.manager.activity.rankunionwar;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossRankUnionWarDebugMgr {
    private static Logger logger = LogManager.getLogger(CrossRankUnionWarDebugMgr.class.getName());

    private static Map<Integer,Map<Integer,Integer>> activityPacketCountMap = new ConcurrentHashMap<>();
    private static Map<Integer,Map<Integer,Integer>> activityPacketSizeMap = new ConcurrentHashMap<>();

    private static long time;

    public static void sendMessageDebug(int activityId,long serverId, long userId, YanQuMessage packet){
        MessageHelper.sendPacket(serverId, userId, packet);
        try {
            if(!activityPacketCountMap.containsKey(activityId)){
                activityPacketCountMap.put(activityId,new ConcurrentHashMap<>());
                activityPacketSizeMap.put(activityId,new ConcurrentHashMap<>());
            }
            Map<Integer,Integer> sendMap = activityPacketCountMap.get(activityId);
            Map<Integer,Integer> sizeMap = activityPacketSizeMap.get(activityId);
            synchronized (sendMap){
                sendMap.put(packet.getCode(),sendMap.getOrDefault(packet.getCode(),0) + 1);
                sizeMap.put(packet.getCode(),sizeMap.getOrDefault(packet.getCode(),0) + packet.getMessage().getSerializedSize());
            }
        }catch (Exception e){
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
    }

    public static void logMessageInfo(){
        try {
            if(System.currentTimeMillis() - time > DateHelper.MINUTE_MILLIONS){
                time = System.currentTimeMillis();
                for(int activityId : activityPacketCountMap.keySet()){
                    Map<Integer,Integer> codeCountMap = activityPacketCountMap.get(activityId);
                    Map<Integer,Integer> codeSizeMap = activityPacketSizeMap.get(activityId);
                    for(int code : codeCountMap.keySet()){
                        logger.info("巅峰商会战活动{}的消息{}发出{}条,大小{}byte",activityId,code,codeCountMap.get(code), codeSizeMap.get(code));
                    }
                    synchronized (codeCountMap){
                        codeCountMap.clear();
                        codeSizeMap.clear();
                    }
                }
            }
        }catch (Exception e){
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
    }
}
